package com.motu.monstercity.server.game.web;


import com.motu.monstercity.module.common.utility.CmdConstant;
import com.motu.monstercity.module.common.utility.EventBusConstant;
import com.motu.monstercity.server.game.timedtask.TimeTaskCmd;
import com.motu.monstercity.server.game.timedtask.TimedTaskManager;
import com.motu.vertx.module.utility.main.MainService;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import com.motu.vertx.module.utility.webtool.BaseWebHandler;
import com.motu.vertx.module.utility.webtool.SearchCondition;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.WebClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class GamehttpgmHandler extends BaseWebHandler{
    private static Logger logger = LoggerFactory.getLogger(GamehttpgmHandler.class);
    // 后台执行修改数据等操作
    public static void handle(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        JsonObject data = json.getJsonObject("data");
        data.put("adminName", adminName);
        WebGMManager.handleMessage(data, res->{
            JsonObject obj = res.result();
            sendHttpResponse(routingContext.response(), obj);
        });
    }

    public static void redisreload(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        try {
            String methodStr = json.getString("method");
            String path = json.getString("path");
            logger.info("redisreload method = " +path+"."+methodStr + "........................................");
            String[] param = methodStr.split("\\.");
            String strClass = param[0];// 类
            String strMethod = param[1];// 静态方法
            String packetPath = path;
            Class<?> threadClazz = Class.forName(packetPath + strClass);
            Method method = threadClazz.getMethod(strMethod, null);
            method.invoke(null, null);
            sendHttpResponse(routingContext.response(), new JsonObject());
        } catch (Exception e) {
            logger.error("handleRoload erorr:"+ Tool.getException(e));
            sendHttpResponseError(routingContext.response(), e.getMessage());
        }
    }


    /***
     * 批量修改服务器状态
     * @param routingContext
     */
    public static void updatebatch(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        HttpServerResponse response = routingContext.response();
        JsonArray params = new JsonArray();
        String sql = "update server_info set ";
        boolean sign = false;
        if(json.containsKey("status")){
            sql += " server_status = ? ";
            sign = true;
            params.add(json.getInteger("status"));
        }
        if(json.containsKey("des")){
            if(sign)
                sql +=",";
            sql += " des = ? ";
            sign = true;
            params.add(json.getString("des"));
        }
        if(json.containsKey("ids")){
            sql += " where  server_id in(";
            JsonArray ids = json.getJsonArray("ids");
            for(int i=0;i<ids.size();i++){
                sql += "?";
                if(i != ids.size() -1){
                    sql += ",";
                }
                params.add(ids.getInteger(i));
            }
            sql += ");";
        }
        logger.debug("updateBatch sql:"+sql+" param:"+params.toString());
        MysqlTool.updateToDb(MysqlClient.getServerPool(), sql, params, handler->{
            if(handler.succeeded()){
                JsonObject result = new JsonObject();
                boolean reload = json.getBoolean("reload");
                if (reload){
                    publishReloadServerList();
                    sendHttpResponse(response, result);
                }else{
                    sendHttpResponse(response, result);
                }
            }else{
                logger.error(handler.cause().getMessage());
                sendHttpResponseError(response, handler.cause().getMessage());
            }
        });
    }
    /***
     * 批量重载服务器状态
     * @param routingContext
     */
    public static void reloadbatch(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        HttpServerResponse response = routingContext.response();
        JsonObject result = new JsonObject();
        publishReloadServerList();
        sendHttpResponse(response, result);
    }

    public static void publishReloadServerList(){
        String ebName = EventBusConstant.getAddress(EventBusConstant.GAME_GM);
        EventBus eventBus = MainService.getVertx().eventBus();
        JsonObject message = new JsonObject();
        message.put("cmd", CmdConstant.GM_CMD_RELOAD);
        JsonObject data = new JsonObject()
                .put("method", "ServerManager.initServerList")
                .put("path", "com.motu.monstercity.module.common.servermanager.");
        message.put("data", data);
        logger.info("execute ebName:"+ebName);
        eventBus.publish(ebName, message);//广播所有的进程重载数据
    }
    public static void commonreload(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        String ebName = EventBusConstant.getAddress(EventBusConstant.GAME_GM);
        EventBus eventBus = MainService.getVertx().eventBus();
        JsonObject message = new JsonObject();
        message.put("cmd", CmdConstant.GM_CMD_RELOAD);
        message.put("data", json);
        logger.info("###execute ebName:"+ebName);
        eventBus.publish(ebName, message);//广播所有的进程重载数据
        sendHttpResponse(routingContext.response(), new JsonObject());
    }

    // 广播重载act_word表
    public static void publishReloadActWord(){
        String ebName = EventBusConstant.getAddress(EventBusConstant.GAME_GM);
        EventBus eventBus = MainService.getVertx().eventBus();
        JsonObject message = new JsonObject();
        message.put("cmd", CmdConstant.GM_CMD_RELOAD);
        JsonObject data = new JsonObject();
        data.put("servertype", new JsonArray().add(1).add(4).add(2));// 游戏服和web服,定时服
        data.put("method", "GameDataManager.initActWord");
        data.put("path", "com.motu.monstercity.server.game.logic.");
        message.put("data", data);
        logger.info("###execute ebName:" + ebName + " data:" + data);
        eventBus.publish(ebName, message);//广播所有的进程重载数据
    }


    /**
     * 检查进程是否加入集群
     * @param routingContext
     * @param json
     * @param adminName
     * @param client
     */
    public static void check(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        String ebName = EventBusConstant.getAddress(EventBusConstant.GAME_GM);
        EventBus eventBus = MainService.getVertx().eventBus();
        JsonObject message = new JsonObject();
        message.put("cmd", CmdConstant.GM_CMD_CHECK);
        message.put("data", new JsonObject().put("type", 0));// 从web进程发起检查
        logger.info("check ebName:" + ebName);
        eventBus.publish(ebName, message);//广播所有的进程重载数据
        sendHttpResponse(routingContext.response(), new JsonObject());
    }

    /**
     * 检查进程是否加入集群, 从定时服进程发起检查
     * @param routingContext
     * @param json
     * @param adminName
     * @param client
     */
    public static void checkByTimedtask(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        JsonObject obj = new JsonObject();
        TimedTaskManager.sendMainTask(TimeTaskCmd.MAIN_CHECK_PROCESS, obj);
        sendHttpResponse(routingContext.response(), new JsonObject());
    }
}
